package drp.snowbell.io.protocol.zip;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import drp.snowbell.exception.CatchException;
import drp.snowbell.util.StrHelper;


public class ZIPURLConnection extends URLConnection {

	InputStream stream;

	protected ZIPURLConnection(URL url) throws MalformedURLException {
		super(url);
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return stream;
	}

	@Override
	public void connect() throws IOException {
		InputStream result = null;
		URL url = this.url;

		String spec = url.getFile();

		int separator = spec.indexOf('#');
		/*
		 * REMIND: we don't handle nested JAR URLs
		 */
		if (separator == -1) {
			throw new MalformedURLException("no # found in url spec:" + spec);
		}

		URL zipFileURL = new URL(spec.substring(0, separator++));
		if (StrHelper.isNullOrEmpty(zipFileURL.getProtocol())) {
		}

		String entryName = spec.substring(separator + 1);

		ZipInputStream zis = new ZipInputStream(zipFileURL.openStream());
		ZipEntry entry = null;

		// check inputStream is ZIP or not
		if ((entry = zis.getNextEntry()) != null) {
			do {
				// System.out.println(entry.getName());
				if (entryName.equals(entry.getName())) {
					result = zis;
					break;
				}
			} while ((entry = zis.getNextEntry()) != null);
		} else {
			CatchException.error(ZIPURLConnection.class, "Given path is not referring ZIP file");
		}
		if (result != null) {
			stream = result;
			this.connected = true;
		}
	}
}